import json
import os

from app.core.conf import ST
from app.schemas.agv import RQAGVInfoMap
from app.sio_agv.agv_socket import AGV


async def get_agv_map(params: RQAGVInfoMap):
    if not params.is_new:
        map_path = ST.get_map_path(params.m_ip)
        if os.path.exists(map_path):
            with open(ST.get_map_path(params.m_ip), "r", encoding="utf-8") as f:
                data = json.load(f)
                return data
        else:
            return get_new_map(params.m_ip)
    else:
        map_data = get_new_map(params.m_ip)
        # 将地图数据缓存起来
        with open(ST.get_map_path(params.m_ip), "w", encoding="utf-8") as f:
            f.writelines(json.dumps(map_data) + "\n")

        return map_data


def get_new_map(ip: str):
    tt15 = AGV.get_agv(ip)
    tt15.send("status", 1, 1300)
    map_info = tt15.receive("status")
    # 然后根据地图的名字去查询地图数据
    tt15.send("config", 1, 4011, {"map_name": map_info["current_map"]})
    map_data = tt15.receive("config")
    return map_data
